package server.jdbcdao;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import server.core.User;
import server.dao.UserDAO;
import server.idatasource.DataSourceFactory;
import server.idatasource.IUserDataSource;

public class UserJdbcDAO implements UserDAO {

	@Override
	public List<User> getAllUsers() {
		DataSourceFactory ds = DataSourceFactory.getInstance();
		IUserDataSource userData = ds.getUserDataSource();

		List<List<String>> result = userData.getAllUsers();
		Iterator<List<String>> it1 = result.iterator();
		User user;
		List<User> userList = new ArrayList<User>();

		while (it1.hasNext()) {
			Iterator<String> it2 = it1.next().iterator();
			user = new User();
			user.setUsername(it2.next());
			user.setName(it2.next());
			user.setPassword(it2.next());
			user.setEmail(it2.next());
			user.setGroupId(Integer.parseInt(it2.next()));
			userList.add(user);
		}
		return userList;
	}

	@Override
	public User getUserByUserName(String username) {
		DataSourceFactory ds = DataSourceFactory.getInstance();
		IUserDataSource userData = ds.getUserDataSource();

		List<String> result = userData.getUserByUserName(username);
		Iterator<String> it = result.iterator();
		User user = new User();
		user.setUsername(it.next());
		user.setName(it.next());
		user.setPassword(it.next());
		user.setEmail(it.next());
		user.setGroupId(Integer.parseInt(it.next()));

		return user;
	}

	@Override
	public String checkUser(String username, String password) {
		DataSourceFactory ds = DataSourceFactory.getInstance();
		IUserDataSource userData = ds.getUserDataSource();

		return userData.checkUser(username, password);
	}

	@Override
	public String insertUser(User user) {
		DataSourceFactory ds = DataSourceFactory.getInstance();
		IUserDataSource userData = ds.getUserDataSource();

		return userData.insertUser(user.getUsername(), user.getName(), user.getPassword(), user.getEmail(), user.getGroupId());
	}

	@Override
	public String deleteUser(String username) {
		DataSourceFactory ds = DataSourceFactory.getInstance();
		IUserDataSource userData = ds.getUserDataSource();

		return userData.deleteUser(username);
	}

	@Override
	public String updateUser(User user) {
		DataSourceFactory ds = DataSourceFactory.getInstance();
		IUserDataSource userData = ds.getUserDataSource();

		return userData.updateUser(user.getUsername(), user.getName(), user.getPassword(), user.getEmail(), user.getGroupId());
	}
}